package org.study.id.other.util;

import lombok.Setter;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 分布式ID生成算法：基于Redis
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年04月23日
 */
public class RedisIdWorker {
    /**
     * 定义开始时间戳：2023-04-23 00:00:00
     */
    private static final long BEGIN_TIMESTAMP = 1682208000L;

    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;
    /**
     * 生成ID的key前缀
     */
    private static final String KEY_PREFIX = "id:generator:";
    @Setter
    private static StringRedisTemplate stringRedisTemplate;

    private RedisIdWorker() {
    }

    public static Long nextId() {
        // 1、生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;
        // 2、生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String tempKey = KEY_PREFIX + date;
        long count = stringRedisTemplate.opsForValue().increment(tempKey);
        stringRedisTemplate.expire(tempKey, 1, TimeUnit.DAYS);
        // 3、拼接并返回
        return timeStamp << COUNT_BITS | count;
    }

    /*public static void main(String[] args) {
        // 用于生成2023-04-23 00:00:00的时间戳
        LocalDateTime time = LocalDateTime.of(2023, 4, 23, 0, 0, 0);
        // 获取当前时间的秒数
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second=" + second);
    }*/
}
